package com.zjun.demo.experimentaldemo

import android.annotation.SuppressLint
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.NoCopySpan
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast

class SecondActivity : AppCompatActivity() {

    private lateinit var tvSpan: TextView

    private lateinit var btnClick: Button

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        tvSpan = findViewById(R.id.tv_span)
        btnClick = findViewById(R.id.btn_click)
        btnClick.setOnClickListener {
            setTextLink()
        }
    }


    private fun setTextLink() {
        val normalText = tvSpan.text.toString()
        val linkText = "《隐私协议》"
        val start = normalText.indexOf(linkText)
        val end = start + linkText.length
        val sp = SpannableString(normalText)
        sp.setSpan(MySpan(), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        tvSpan.setHintTextColor(Color.TRANSPARENT)
        tvSpan.text = sp
        tvSpan.movementMethod = LinkMovementMethod.getInstance()
    }

    inner class MySpan : ClickableSpan(), NoCopySpan {
        override fun onClick(widget: View) {
            Toast.makeText(this@SecondActivity, "点击了隐私协议!", Toast.LENGTH_SHORT).show()
        }

        override fun updateDrawState(ds: TextPaint) {
            super.updateDrawState(ds)
            ds.color = getColor(R.color.black)
            ds.isUnderlineText = false
        }

    }
}
